package com.find.memories.gallery;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.find.memories.BaseFragment;
import com.find.memories.BuildConfig;
import com.find.memories.MainActivity;
import com.find.memories.R;
import com.find.memories.util.Utils;

public class FragmentGallery extends BaseFragment implements OnItemClickListener {

    private GridView mGridView;
    private TextView mTvEmpty;
    private FragmentGalleryAdapter mAdapter;
    private int mImageThumbSize;
    private int mImageThumbSpacing;
    private final String TAG = "FragmentGallery";
    private ArrayList<PhotoItem> items = new ArrayList<PhotoItem>();
    private MainActivity mActivity;
    
    public static FragmentGallery init() {
        FragmentGallery fragment = new FragmentGallery();

        // Supply val input as an argument.
        Bundle args = new Bundle();
        fragment.setArguments(args);

        return fragment;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mActivity = (MainActivity) getActivity();
        
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
        mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
        
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_gallery_view, container, false);
        mGridView = (GridView) v.findViewById(R.id.gridView);
        mGridView.setOnItemClickListener(this);
        mTvEmpty = (TextView) v.findViewById(R.id.tvEmpty);
        
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @TargetApi(VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onGlobalLayout() {
                        if (mAdapter.getNumColumns() == 0) {
                            final int numColumns = (int) Math.floor(
                                    mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                            if (numColumns > 0) {
                                final int columnWidth =
                                        (mGridView.getWidth() / numColumns) - mImageThumbSpacing;
                                mAdapter.setNumColumns(numColumns);
                                mAdapter.setItemHeight(columnWidth);
                                if (BuildConfig.DEBUG) {
                                    Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                                }
                                if (Utils.hasJellyBean()) {
                                    mGridView.getViewTreeObserver()
                                            .removeOnGlobalLayoutListener(this);
                                } else {
                                    mGridView.getViewTreeObserver()
                                            .removeGlobalOnLayoutListener(this);
                                }
                            }
                        }
                    }
                });

        return v;
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        mAdapter = new FragmentGalleryAdapter(getActivity(), items);
        mGridView.setAdapter(mAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public ArrayList<Integer> getExistDays(int year, int month) {
        if (month == 0)
            return null;
        
        ArrayList<Integer> arrItems = new ArrayList<Integer>();
        
        ContentResolver cr = getActivity().getContentResolver();
        
        String strDate =  String.format("%s-%s-01 00:00:00", year, month);
        String strDate2 =  String.format("%s-%s-31 23:59:59", year, month);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        Date d2 = null;
        
        try {
            d = format.parse(strDate);
            d2 = format.parse(strDate2);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Long time = d.getTime();
        Long time2 = d2.getTime();
        
        String strSortOrder = Images.ImageColumns.DATE_TAKEN + " DESC";
        String[] whereValues = { "" + time,  "" + time2};
        String where = "? <= " + Images.ImageColumns.DATE_TAKEN + " AND " + Images.ImageColumns.DATE_TAKEN + " <= ?";
        Cursor c = cr.query(Images.Media.EXTERNAL_CONTENT_URI , null , where, whereValues, strSortOrder);
        
        int count = 0;
        
        try {
            if (c != null && c.getCount() > 0){
                c.moveToFirst();
                do{
                    String retDate = c.getString(c.getColumnIndexOrThrow(ImageColumns.DATE_TAKEN));
                    String day = new SimpleDateFormat("dd").format(Long.valueOf(retDate));
                    
                    int nDay = Integer.valueOf(day);
                    if (!arrItems.contains(nDay))
                        arrItems.add(nDay);
                    
                } while (c.moveToNext());
            }
        } catch ( Exception e ){
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        
        Collections.sort(arrItems, new NoAscCompare());
        
        return arrItems;
    }

    @Override
    public void onRefresh(int nYear, int nMonth, int nDay) {

        items = new ArrayList<PhotoItem>();
        
        ContentResolver cr = getActivity().getContentResolver();
        
        String strDate =  String.format("%s-%s-%s 00:00:00", nYear, nMonth, nDay);
        String strDate2 =  String.format("%s-%s-%s 23:59:59",  nYear, nMonth, nDay);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        Date d2 = null;
        
        try {
            d = format.parse(strDate);
            d2 = format.parse(strDate2);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Long time = d.getTime();
        Long time2 = d2.getTime();
        
        String strSortOrder = Images.ImageColumns.DATE_TAKEN + " DESC";
        String[] whereValues = { "" + time,  "" + time2};
        String where = "? <= " + Images.ImageColumns.DATE_TAKEN + " AND " + Images.ImageColumns.DATE_TAKEN + " <= ?";
        Cursor c = cr.query(Images.Media.EXTERNAL_CONTENT_URI , null , where, whereValues, strSortOrder);
        
        int count = 0;
        
        try {
            if (c != null && c.getCount() > 0){
                c.moveToFirst();
    
                do{
                    PhotoItem item = new PhotoItem() ;
                    
                    item.setData(c.getString(c.getColumnIndexOrThrow(ImageColumns.DATA)));
                    item.setId(c.getString(c.getColumnIndexOrThrow(ImageColumns._ID)));
                    item.setName(c.getString(c.getColumnIndexOrThrow(ImageColumns.DISPLAY_NAME)));
                    item.setRegDate(c.getString(c.getColumnIndexOrThrow(ImageColumns.DATE_TAKEN)));
                    
                    items.add(item);
                    
                    count++;
                    
                } while (c.moveToNext());
            }
        } catch ( Exception e ){
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        Log.d("Test", "count : " + count);
        
        mTvEmpty.setVisibility(View.GONE);
        
        if (items.isEmpty()) {
            if (mAdapter.getCount() == 0)
                mTvEmpty.setVisibility(View.VISIBLE);
            return;
        }
        
        mAdapter.setItems(items);
    }

    @Override
    public void onInit() {
        mAdapter.setItems(items);
        mTvEmpty.setVisibility(View.VISIBLE);
    }

}
